package com.yet.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.springframework.context.ApplicationEvent;

import com.yet.container.registry.RegistryMeta.ServiceMeta;

/**
 * 注册事件
 */
public class RegistryEvent extends ApplicationEvent {

	private static final long serialVersionUID = 1L;

	/**
	 * 事件类型
	 */
	public enum Type {
		/** 注册 */
		REGISTRY,
		/** 下架 */
		UNREGISTRY,
		/** 修改 */
		UPDATE;

		public static final Map<String, Type> holder = new HashMap<>(4);
		static {
			holder.put("REGISTRY", REGISTRY);
			holder.put("UNREGISTRY", UNREGISTRY);
		}

		public static Type str2Type(String name) {
			return Optional.ofNullable(holder.get(name)).orElseThrow(() -> new RuntimeException("未知的事件:" + name));
		}

		public static Type str2Type(TreeCacheEvent.Type type) {
			switch (type) {
			case NODE_ADDED:
				return REGISTRY;
			case NODE_UPDATED:
				return UPDATE;
			case NODE_REMOVED:
				return UNREGISTRY;
			default:
				return null;
			}
		}

		@Override
		public String toString() {
			return this.name();
		}
	}

	private final String name;

	private final Type type;

	private final ServiceMeta meta;

	public RegistryEvent(String name, ServiceMeta meta, Type type) {
		super(meta);
		this.name = name;
		this.meta = meta;
		this.type = type;
	}

	public Type getType() {
		return type;
	}

	public ServiceMeta getMeta() {
		return meta;
	}

	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return "RegistryEvent [name=" + name + ", type=" + type + ", meta=" + meta + "]";
	}

}
